/*
 * bar.c
 *
 *  Created on: Jan 6, 2012
 *      Author: ian
 */
#include <stdio.h>
#include <avr/pgmspace.h>

#include "lcd.h"
#include "bar.h"

/* local prototypes */
unsigned int barColor( stBar *bar, unsigned char v );


void BAR_init( stBar *bar )
{
	LCD_Rect( bar->x, bar->y, bar->x + bar->w + 1, bar->y + bar->h + 1, THIN, white );
	bar->redraw = true;
}


void BAR_update( stBar *bar, unsigned char newval )
{
	unsigned char oldVal;
	unsigned char i;
	unsigned int c;

	oldVal = bar->value;
	bar->value = newval;

	if( bar->redraw ) {
		c = bar->colorLow;
		for( i = 0; i < bar->w; i++ ) {
			c = barColor( bar, i );
			LCD_Draw( bar->x + 1 + i, bar->y + 1, bar->x + 1 + i, bar->y + bar->h, THIN, c );
		}
		bar->redraw = false;
	}
	else {
		if( newval < oldVal ) {
			for( i = newval; i <= oldVal; i++ ) {
				LCD_Draw( bar->x + 1 + i, bar->y + 1, bar->x + 1 + i, bar->y + bar->h, THIN, black );
			}
		}
		else if( newval > oldVal ) {
			for( i = oldVal; i <= newval; i++ ) {
				LCD_Draw( bar->x + 1 + i, bar->y + 1, bar->x + 1 + i, bar->y + bar->h, THIN, barColor( bar, i ) );
			}
		}
	}
}


unsigned int barColor( stBar *bar, unsigned char v )
{
	if( v >= bar->value ) {
		return black;
	}
	else if( v < bar->normalLow ) {
		return bar->colorLow;
	}
	else if( v > bar->normalHigh ) {
		return bar->colorHigh;
	}
	else {
		return bar->colorNormal;
	}
}
